//
//  RegistarViewController.m
//  FootPrint
//
//  Created by alex tao on 2/26/13.
//  Copyright (c) 2013 alex tao. All rights reserved.
//

#import "RegistarViewController.h"
#import "RegisterRequest.pb.h"
#import "RegisterResponse.pb.h"
#import "MatchFriendViewController.h"

@interface RegistarViewController ()

@end

@implementation RegistarViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        _parser = [[CommonParser alloc] init];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.navigationController.navigationBarHidden = YES;
    
    UIImage* imgNormal =[[UIImage imageNamed:@"btn_bg_normal.png"] stretchableImageWithLeftCapWidth:10 topCapHeight:0];
    UIImage* imgPress =[[UIImage imageNamed:@"btn_bg_press.png"] stretchableImageWithLeftCapWidth:10 topCapHeight:0];
    
    [_btnSubmit setBackgroundImage:imgNormal forState:UIControlStateNormal];
    [_btnSubmit setBackgroundImage:imgPress forState:UIControlStateHighlighted];
    
    UITapGestureRecognizer *tapGr = [[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(viewTapped:)] autorelease];
    tapGr.cancelsTouchesInView = NO;
    [self.view addGestureRecognizer:tapGr];
    // Do any additional setup after loading the view from its nib.
}


- (void) viewTapped:(UITapGestureRecognizer*)tapGr{
    [self hideKeyBord];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc {
    [_parser release];
    [_contentScroll release];
    [_phoneText release];
    [_passText release];
    [_repeatPassText release];
    [_nickNameText release];
    [_btnBack release];
    [_btnSubmit release];
    [super dealloc];
}

- (void)viewDidUnload {
    [self setContentScroll:nil];
    [self setPhoneText:nil];
    [self setPassText:nil];
    [self setRepeatPassText:nil];
    [self setNickNameText:nil];
    [self setBtnBack:nil];
    [self setBtnSubmit:nil];
    [super viewDidUnload];
}

- (IBAction)back {
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)actionSubmit
{
    NSString * phone = _phoneText.text;
    NSString * pass = _passText.text;
    NSString * repeatPass = _repeatPassText.text;
    NSString * nickName = _nickNameText.text;
    
    if (phone.length == 0 || pass.length == 0 || repeatPass.length == 0) {
        [[[iToast makeText:@"用户名密码不能为空!"] setDuration:2000] show];
        return;
    }
    
    if (![pass isEqualToString:repeatPass]) {
        [[[iToast makeText:@"两次密码输入不同!"] setDuration:2000] show];
        return;
    }
    
    if (![GToolUtil isMobileNumber:phone]) {
        [[[iToast makeText:@"无效的电话号码!"] setDuration:2000] show];
        return;
    }
    
    [_phoneText resignFirstResponder];
    [_passText resignFirstResponder];
    [_repeatPassText resignFirstResponder];
    [_nickNameText resignFirstResponder];
    [_contentScroll setContentOffset:CGPointZero animated:YES];

    RegisterRequestMessage_Builder * builder = [[[RegisterRequestMessage builder] setPhoneNo:phone] setPassword:pass];
    if (nickName) {
        builder = [builder setNickName:nickName];
    }
    
    NSData * data = [[builder build] data];
    if (data) {
        [_parser noCacheRequestURL:URL_USER_REGISTER postData:data completion:^(NSData * resultData) {
            RegisterResponseMessage * regResp = [RegisterResponseMessage parseFromData:resultData];
            if (regResp && regResp.resultCode == 0 && regResp.userId > 0) {
                [GConfig setUserId:regResp.userId];
                [GConfig setUserLoginInfo:[NSDictionary dictionaryWithObjectsAndKeys:regResp.userName, @"user", phone, @"phone", pass, @"pass", nil]];
                
                [self showSuccessAlert];
               
            } else {
                
                switch (regResp.resultCode) {
                    
                    case 1:
                        [[[iToast makeText:@"用户名重复!"] setDuration:2000] show];
                        break;
                    case 2:
                        [[[iToast makeText:@"手机号码已存在!"] setDuration:2000] show];
                        break;
                    case 3:
                        [[[iToast makeText:@"密码格式不对!"] setDuration:2000] show];
                        break;
                    case 4:
                        [[[iToast makeText:@"注册失败，错误码4!"] setDuration:2000] show];
                        break;
                    default:
                        [[[iToast makeText:@"注册信息出错!"] setDuration:2000] show];
                        break;
                }
            }
        } fail:^(NSError * err) {
            [[[iToast makeText:@"注册失败!"] setDuration:2000] show];
        }];
    }
}


-(void)hideKeyBord{

    [_phoneText resignFirstResponder];
    [_passText resignFirstResponder];
    [_repeatPassText resignFirstResponder];
    [_nickNameText resignFirstResponder];
    [_contentScroll setContentOffset:CGPointZero animated:YES];
    
}

- (void) showSuccessAlert {

    _alertView = [[UIAlertView alloc] initWithTitle:@"注册成功" message:@"您已注册成功，是否要匹配通讯录中足迹好友？" delegate:self cancelButtonTitle:@"匹配好友" otherButtonTitles:@"直接进入", nil];
    [_alertView show];
    
     
    
}


- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if(alertView == _alertView && buttonIndex == [alertView cancelButtonIndex]){
        
        MatchFriendViewController * matchVC = [[[MatchFriendViewController alloc] initWithNibName:@"MatchFriendViewController" bundle:nil] autorelease];
        [self.navigationController pushViewController:matchVC animated:YES];
        
    } else if(alertView == _alertView){
        [[NSNotificationCenter defaultCenter] postNotificationName:NOTIFY_LOGIN_SUCCESS object:nil];
    }
}

#pragma mark - UITextFieldDelegate

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    [_contentScroll setContentOffset:CGPointMake(0, 65) animated:YES];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    if(textField.tag == 0){
        [_phoneText resignFirstResponder];
        [_nickNameText becomeFirstResponder];
    } else if(textField.tag == 1){
        [_nickNameText resignFirstResponder];
        [_passText becomeFirstResponder];
    
    } else if(textField.tag == 2){
        [_passText resignFirstResponder];
        [_repeatPassText becomeFirstResponder];
    } else {
        [self hideKeyBord];
    }
    return YES;

}

@end
